<?
//	*****************************************
//	SbSE metadata fetch component
//	v1.0.3 / 11.09.18
//	Required:
//	lib 0.9.1
//	*****************************************

require_once E.'_lib/_const.php';

class TREEDATA {

	var $id_data;
	var $id_parent;
	var $assoc;
	var $data;
	var $varname;
	
	var $res;
	
	function TREEDATA() {

		$this->data = array();
		$this->res = 0;

		$this->id_data = 0;
		$this->id_parent = 0;
		$this->assoc = '';
		$this->varname = '';
		$this->filter = 0;
		$this->order = 'name';
	}
	
	function init($params) {
		
		if ($temp = $params['id'])			$this->id_data = $temp;
		if ($temp = $params['parent'])	$this->id_parent = $temp;
		if ($temp = $params['assoc'])		$this->assoc = $temp;
		if ($temp = $params['varname'])	$this->varname = $temp;
		if ($temp = $params['order'])		$this->order = $temp;
		
		if (($temp = $params['filter']) && is_callable($temp))	$this->filter = $temp;
		
		$this->data = $this->apply($this->id_parent, $this->fetch($this->id_parent));

		return sizeof($this->data);
	}

	function apply($p, $data) {

		if (!$p) return $data[0];

		$res = array();
		if (!is_array($p)) $p = array($p);
		$pr = implode(',', $p);
		
		if ($d = datafetch('db_list', array('table' => tb('data'),		// get records with empty 'assoc' (i.e. for all langs) or with corresponding 'assoc'
			'where' => "(id_data={$this->id_data}) AND
			(id in ($pr)) AND
			((assoc IS NULL) OR (assoc='') OR INSTR(assoc,'{$this->assoc}')!=0)", 
			'index' => "id", 'order' => $this->order ))) {
			
			foreach($d as $k => $v)
				if (isset($data[$k])) {
					$res[$k] = $v;
					$res[$k]['data'] = $data[$k];
					if ($this->filter) $res[$k]['filter'] = call_user_func_array($this->filter, array($this, $k, $v));
				}
		}
			else $res = $data;
		
		return $res;
	}


	function fetch($p) {
		
		$data = array();
		if (!is_array($p)) $p = array($p);
		$pr = implode(',', $p);
		
		if ($d = datafetch('db_list', array('table' => tb('data'),		// get records with empty 'assoc' (i.e. for all langs) or with corresponding 'assoc'
			'where' => "(id_data={$this->id_data}) AND
			(id_parent in ($pr)) AND
			((assoc IS NULL) OR (assoc='') OR INSTR(assoc,'{$this->assoc}')!=0)", 
			'index' => "id", 'order' => $this->order ))) {
			
			foreach($d as $k => $v) {
				if (!isset($data[$v['id_parent']])) $data[$v['id_parent']] = array();
				$data[$v['id_parent']][$k] = $v;

				if ($this->filter) $data[$v['id_parent']][$k]['filter'] = call_user_func_array($this->filter, array($this, $k, $v));
			}

			if (sizeof($temp = $this->fetch(array_keys($d)))) {					// recursion
				foreach ($temp as $newId => $newTag) // for every 2nd 
					foreach($data as $curId => $curTag)
						if (isset($curTag[$newId])) {
							$data[$curId][$newId]['data'] = $newTag;
							break;
						}
			}
		}
		
		return $data;
	}
}

?>